package com.calabar.distr.lock;

import java.sql.*;

public class DBDistrLock {

    private Connection connection = null;

    /**
     * jdbc数据库连接
     * @return
     */
    public Connection createJDBCConnection() {
        String driver = "com.mysql.jdbc.Driver";
        String url = "jdbc:mysql://localhost:3306/distr_lock?useUnicode=true&characterEncoding=UTF-8";
        String username ="root";
        String password = "123456";
        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 执行任务
     */
    public void executeTask() throws SQLException, InterruptedException {

        // 关闭自动事务
        connection.setAutoCommit(false);

        // 获取锁
        String sql = "select method_name from my_lock where id=1 for update";
        PreparedStatement ps = connection.prepareStatement(sql);
        ResultSet rs = ps.executeQuery();

        // 执行任务
        for (int i = 0; i < 200; i++) {
            Thread.sleep(1000l);
            System.out.println("等待"+i+"秒");
        }

        // 释放锁
        String commitSQL = "commit";
        PreparedStatement commitPS = connection.prepareStatement(commitSQL);
        commitPS.execute();
    }

    public static void main(String[] args) throws SQLException, InterruptedException {
        DBDistrLock lock = new DBDistrLock();
        lock.createJDBCConnection();
        lock.executeTask();
    }
}
